package gui.nodes;

import gui.AbstractViewPane;
import gui.MainController;
import gui.MatiereUIConsulter;
import gui.UEUIConsulter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.tree.DefaultMutableTreeNode;

import utility.Record;
import business.UEBL;

public class UENode extends AbstractNode {
	int ueId;
	String ueName;
	int semestreId;
	DefaultMutableTreeNode UENode;
	UERoot parentNode;

	public UENode(UERoot parentNode, Record ueRec,int semId) {
		super();
		this.parentNode = parentNode;
		ueId = ueRec.getId();
		ueName = ueRec.getLibelle();
		semestreId = semId;
	}

	@Override
	public JPopupMenu makePopup() {
		return new Popup();
	}

	@Override
	public String getNodeName() {
		return ueName;
	}

	public void loadPrimaryViewPane() {
		AbstractViewPane newViewPane = new UEUIConsulter(parentNode,
AbstractViewPane.ViewMode.CONSULTATION,ueId,semestreId);
		MainController.getInstance().setViewPane(newViewPane);
	}	
	
	public void loadModifierViewPane() {
		AbstractViewPane newViewPane = new UEUIConsulter(parentNode,
AbstractViewPane.ViewMode.MODIFICATION,ueId,semestreId);
		MainController.getInstance().setViewPane(newViewPane);
	}
	
	public void loadAjouterViewPane() {
		AbstractViewPane newViewPane = new MatiereUIConsulter(parentNode,
AbstractViewPane.ViewMode.AJOUT,-1,ueId);
		MainController.getInstance().setViewPane(newViewPane);
	}
	
	public void loadSupprimerViewPane() {
		if (supprimer() == JOptionPane.YES_OPTION) {
			UEBL ueBL = new UEBL(ueId);
			ueBL.supprimerUE();
		}
		((AbstractNode)parent).refresh();
	}
	
	private class Popup extends JPopupMenu implements ActionListener {
		JMenuItem ajouter = new JMenuItem("Ajouter une matière");
		JMenuItem modifier = new JMenuItem("Modifier l'UE");
		JMenuItem supprimer = new JMenuItem("Supprimer l'UE");

		public Popup() {
			ajouter.addActionListener(this);
			modifier.addActionListener(this);
			supprimer.addActionListener(this);
			add(ajouter);
			add(modifier);
			add(supprimer);
		}

		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == ajouter) {
				loadAjouterViewPane();
			}
			if (e.getSource() == modifier) {
				loadModifierViewPane();
			}
			if (e.getSource() == supprimer) {
				loadSupprimerViewPane();
			}
		}
	}

	@Override
	public void expandHook() {
		this.removeAllChildren();

		UEBL ueBL = new UEBL(this.ueId);
		
		System.out.println(ueBL.getDescriptionUE());

		for (Record matiereRec : ueBL.getListeMatiere()) {
			MatiereNode matNode = new MatiereNode(this, matiereRec,ueId);
			add(matNode);
		}
	}
	
	public int supprimer() {
		return JOptionPane.showConfirmDialog(
			    null,
			    "Êtes vous sûr de vouloir supprimer l'UE\n"+
			    //ensBL.getName()+" "+ensBL.getPrenom()+
			    " ?",
			    "Avertissement",
			    JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
		
	}

}